package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

import java.util.Calendar;

/**
 * Takes a date or datetime value and returns the corresponding value for the
 * last day of the month. Returns NULL_KEY if the argument is invalid.
 *
 * <pre>
 * mysql> SELECT LAST_DAY('2003-02-05');
 *         -> '2003-02-28'
 * mysql> SELECT LAST_DAY('2004-02-05');
 *         -> '2004-02-29'
 * mysql> SELECT LAST_DAY('2004-01-01 01:01:01');
 *         -> '2004-01-31'
 * mysql> SELECT LAST_DAY('2003-03-32');
 *         -> NULL_KEY
 * </pre>
 */
public class LastDay extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        java.sql.Timestamp timestamp = Type.TimestampType.convert(args[0]);
        Calendar cal = Calendar.getInstance();
        cal.setTime(timestamp);

        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        Type type = getReturnType();
        return type.convert(cal.getTime());
    }

    public Type getReturnType() {
        return Type.DateType;
    }

    public String[] getFunctionNames() {
        return new String[]{"LAST_DAY"};
    }
}
